package com.readpost.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.readpost.doman.Dto.DraftArticleDto;
import com.readpost.doman.Entity.Articles;
import com.readpost.doman.PageBean;
import com.readpost.doman.Result;
import com.readpost.mapper.ArticleMapper;
import com.readpost.service.ArticlesService;
import com.readpost.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticlesService {

    @Autowired
    private ArticleMapper articlesMapper;

    /**
     * 发布文章
     * @param articles 文章对象
     */
    @Override
    public void addArticle(Articles articles) {
        articlesMapper.addArticle(articles);
    }

    /**
     * 保存草稿
     * @param articles 文章对象
     */
    @Override
    public void createArticle(DraftArticleDto articles , Integer userId) {
        int i = articlesMapper.hasDraftArticle(Articles.Status.draft,userId);
        articles.setUserId(userId);
        articles.setStatus("draft");
        if(i>0){
            articlesMapper.upCreateArticle(articles);
        }else {
            articlesMapper.addCreateArticle(articles);
        }
    }

    /**
     * 已保存草稿
     * @param userId 文章对象
     */
    @Override
    public Articles contentDraftArticle(Integer userId) {
        int i = articlesMapper.hasDraftArticle(Articles.Status.draft,userId);
        if(i>0){
            return  articlesMapper.getContentDraftArticle(Articles.Status.draft,userId);
        }else {
            return  null;
        }
    }


    @Override
    public void publishArticle(DraftArticleDto articles, Integer userid) {

    }

    /**
     * 文章列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param categoryId 分类ID
     * @param state 状态
     * @return 文章列表
     */
    @Override
    public PageInfo<Articles> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {

        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> o = ThreadLocalUtil.get();
        Integer userId = (Integer) o.get("userid");
        List<Articles> list = articlesMapper.list(categoryId,state,userId);

        //        PageBean<Articles> pb = new PageBean<>();
        //        Map<String,Object> o = ThreadLocalUtil.get();
        //        Integer userId = (Integer) o.get("userid");
        //        //执行查询
        //        List<Articles> list = articlesMapper.list(categoryId,state,userId);
        //        PageInfo<Articles> p=(PageInfo<Articles>) list;
        return new PageInfo<>(list);
    }
}
